package com.ht.common;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class FileUpload {
    public static String upload(MultipartFile file, HttpSession session, String filePath){
        if(file==null || file.getOriginalFilename()==null||file.getOriginalFilename().equals("")){
            System.out.println("文件为空");
            return null;
        }
        String picName = UUID.randomUUID().toString();//随机的UUID
        // 截取文件的扩展名(如.jpg)
        String oriName = file.getOriginalFilename();  //获取上传时的文件名 111.jpg
        System.out.println("图片名字："+oriName);
        String extName = oriName.substring(oriName.lastIndexOf("."));  //截取后缀 .jpg
        String path = session.getServletContext().getRealPath("\\");//获取项目路径
        String dirName = "\\upload\\"+filePath+"\\"; //这里放置上传的年月日，如果全部放到一个文件夹里，文件太多，不容易找
        System.out.println(path);
        System.out.println(path+dirName);
        File dirFile = new File(path+dirName);
        if(!dirFile.exists()){  //创建文件夹
            dirFile.mkdirs();
        }

        String newFileName = picName + extName; //新文件名2hj35523k4k53-234h324.jpg
        File targetFile = new File(path+dirName , newFileName);

        try {
            file.transferTo(targetFile);  // 保存文件
        } catch (IOException e) {
            e.printStackTrace();
        }

        return dirName+newFileName; // upload/face/123324.jpg
    }
}